<?php

class Oauth extends MY_Controller {

        public function oauthcode() {
            $memberModel = new Member();
            $code=$this->input->get('code');
            if (!empty($code)) {
                $accesstoken = $this->getWechat()->wxOauthAccessToken($code);
            }

            $openid = $accesstoken['openid'];
            $tokenvalue = $accesstoken['access_token'];
            $refreshtoken = $accesstoken['refresh_token'];
            //var_dump($accesstoken);

            $userinfo = $memberModel->getUserInfoFromDb($openid);
            $now = time();
            if(empty($userinfo)) {
                $oauthUser = $this->getWechat()->wxOauthUser($tokenvalue,$openid);

                $userinfo = array(
                    'openid' => $openid,
                    'accesstoken' => $tokenvalue,
                    'nickname' => $oauthUser['nickname'],
                    'sex' => $oauthUser['sex'] == '1' ? '男' : '女',
                    'province' => $oauthUser['province'],
                    'city' => $oauthUser['city'],
                    'headimgurl' => $oauthUser['headimgurl'],
                    'lastupdatetime' => $now,
                    'tokenctime'=>$now,
                    'refreshtoken'=>$refreshtoken
                );
                $this->db->insert('t_user', $userinfo);
            } else {
                //update token.
                $this->db->update('t_user',array(
                    'accesstoken'=>$tokenvalue,
                    'refreshtoken'=>$refreshtoken,
                    'tokenctime'=>$now
                ),array('openid'=>$openid));

                $userinfo['accesstoken']=$tokenvalue;
                $userinfo['refreshtoken']=$refreshtoken;
                $userinfo['tokenctime']=$now;

            }

            $_SESSION['userinfo'] = $userinfo;
            $_SESSION['openid'] = $openid;

            $redirect_url = $this->input->get('redirect');

            //echo $redirect_url;

            redirect($redirect_url!=null?$redirect_url:'welcome/index');
        }
}